﻿using System;
using System.Windows.Forms;

namespace Awesome.Extensions.WinForms
{
    public static class ControlEx
    {
        public static TResult BeginInvoke<TControl, TResult>(this TControl control, Func<TControl, TResult> action)
            where TControl : Control
        {
            return (TResult) control.BeginInvoke(action, new object[] {control});
        }

        public static void BeginInvoke<TControl>(this TControl control, Action<TControl> action)
            where TControl : Control
        {
            control.BeginInvoke(action, new object[] {control});
        }

        public static void Invoke<TControl>(this TControl control, Action<TControl> action)
            where TControl : Control
        {
            if (control.InvokeRequired)
            {
                control.Invoke(action, new object[] {control});
            }
            else
            {
                action(control);
            }
        }

        public static TResult Invoke<TControl, TResult>(this TControl control, Func<TControl, TResult> action)
            where TControl : Control
        {
            if (control.InvokeRequired)
            {
                return (TResult) control.Invoke(action, new object[] {control});
            }
            
            return action(control);
        }
    }
}
